package util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 返回json数据工具类
 * response 请求响应
 * data 返回数据对象
 */
public class ResposeUtil {
    public static void write(Object data, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8"); //设置响应字符集
        response.setHeader("Content-Type", "application/json"); // 响应数据类型 头信息
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            // JSON.toJSONString(result)要获取完整的json字符串，每一个字段都要有set和get方法，不然会缺少某个字段
            writer = response.getWriter();
            writer.write(JSON.toJSONString(data,SerializerFeature.WriteMapNullValue));
            writer.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
